// login & register
const express = require('express')
const router = express.Router()
const bcrypt = require('bcrypt')
const jwt = require('jsonwebtoken')
const User = require('../../models/User')
const keys = require('../../config/keys')
const passport = require('passport')

/**
 *  $route POST api/users/register
 * @desc 返回的请求的json数据
 * @access public
 */

router.post('/users/register', (req, res) => {
  // 查询数据库中是否拥有此身份证
  User.findOne({ number: req.body.number }).then((user) => {
    if (user) {
      return res.status(400).json({ status: '400', message: '此身份证号已经被注册!' })
    } else {
      const newUser = new User({
        name: req.body.name,
        number: req.body.number,
        telephone: req.body.telephone,
        password: req.body.password,
        sex: req.body.sex,
        age: req.body.age,
        role: req.body.role,
      
      })
      bcrypt.genSalt(10, (err, salt) => {
        bcrypt.hash(newUser.password, salt, (err, hash) => {
          // Store hash in your password DB.
          if (err) throw err
          newUser.password = hash
          newUser
            .save()
            .then(() => {
              return res.json({ status: 200, success: true, message: '用户注册成功' })
            })
            .catch((error) => {
              return res.status(400).json({ status: 400, error, message: '注册失败了！'})
            })
        })
      })
    }
  })
})

/**
 *  $route POST api/users/login
 * @desc 返回的请求的json数据
 * @access public
 */
router.post('/users/login', (req, res) => {
  const number = req.body.number
  const password = req.body.password
  User.findOne({ number }).then((user) => {
    if (!user) {
      return res.status(400).json({ status: 400, message:'此用户不存在，请先注册!', error: '此用户不存在，请先注册!' })
    }

    // 密码匹配
    bcrypt.compare(password, user.password).then((isMatch) => {
      if (isMatch) {
        const rule = {
          id: user.id,
          number: user.number,
          name: user.name,
          telephone: user.telephone,
          sex: user.sex,
          age: user.age,
          role: user.role
        }
        // jwt.sign("规则", "加密名字", "过期时间", "箭头函数")
        jwt.sign(rule, keys.secretOrKey, { expiresIn: 36000 }, (err, token) => {
          if (err) throw err
          res.json({
            status: 200,
            message: '登录成功',
            success: true,
            token: 'Bearer ' + token
          })
        })
      } else {
        return res.status(400).json({ status: 400, message: '用户名或者密码错误', error: '用户名或者密码错误' })
      }
    })
  })
})

/**
 *  $route POST api/users/current
 * @desc return current user
 * @access private
 */
router.get('/users/userInfo', passport.authenticate('jwt', { session: false }), (req, res) => {
  User.findOne({ _id: req.query.id }).then((user) => {
    res.json({
      status: 200,
      success: true,
      message: '获取个人信息成功',
      data: {
        id: user.id,
        name: user.name,
        number: user.number,
        telephone: user.telephone,
        sex: user.sex,
        age: user.age,
        role: user.role
      }
    })
  })
})

module.exports = router
